package org.example.niobitfile;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
/**
 * {@code @projectName} bitmap17
 * {@code @Author} huzhengyang
 * {@code @Create} 2024/4/26 12:55
 */
public class LargeTextFileProcessingExample {
    public static void main(String[] args) {
        String sourceFilePath = "largefile.txt";
        String targetFilePath = "processedfile.txt";

        try (FileChannel sourceChannel = FileChannel.open(Paths.get(sourceFilePath), StandardOpenOption.READ);
             FileChannel targetChannel = FileChannel.open(Paths.get(targetFilePath),
                     StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

            long fileSize = sourceChannel.size();
            long bytesTransferred = 0;
            ByteBuffer buffer = ByteBuffer.allocate(8192); // 缓冲区大小，根据需要调整

            Charset charset = Charset.forName("UTF-8");
            CharsetDecoder decoder = charset.newDecoder();

            while (bytesTransferred < fileSize) {
                long bytesToTransfer = Math.min(buffer.remaining(), fileSize - bytesTransferred);
                sourceChannel.read(buffer, bytesTransferred);
                buffer.flip();

                CharBuffer charBuffer = decoder.decode(buffer);

                // 处理解析后的文本数据
                processBuffer(charBuffer);

                ByteBuffer encodedBuffer = charset.encode(charBuffer);
                targetChannel.write(encodedBuffer);
                buffer.clear();

                bytesTransferred += bytesToTransfer;
            }

            System.out.println("File processing complete.");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void processBuffer(CharBuffer charBuffer) {
        // 处理解析后的文本数据
        while (charBuffer.hasRemaining()) {
            char c = charBuffer.get();
            // 在这里进行处理，可以根据需求进行解析、转换、加密等操作
            // 以下是一个示例，将每个字符转换为大写
            char processedChar = Character.toUpperCase(c);
            // 将处理后的字符写回到缓冲区
            charBuffer.put(processedChar);
        }
    }
}